package com.playball.lottery.frm.yhzx;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.playball.lottery.R;
import com.playball.lottery.ApplicationData;
import com.playball.lottery.base.BaseActivity;
import com.playball.lottery.customview.ShowTipDialog;
import com.playball.lottery.nt.GetRequestParams;
import com.playball.lottery.util.ConvertJsonToList;
import com.playball.lottery.util.province.City;
import com.playball.lottery.util.province.Province;
import com.playball.lottery.util.province.ProvinceParse;


/**
 * 安全中心 - 银行卡
 * 
 * @author tanglizhong
 * @version 2014-3-26 上午10:37
 */
public class ScBankCardActivity extends BaseActivity {

	/**
	 * 银行卡信息布局
	 */
	private View view_sc_bankcard_info;
	/** 持卡人姓名 */
	private TextView yhzx_sc_tv_bankcard_name;
	/** 开户银行 */
	private TextView yhzx_sc_tv_bankcard_addr;
	/** 银行卡号 */
	private TextView yhzx_sc_tv_bankcard_number;

	/**
	 * 添加银行卡布局
	 */
	private View view_sc_bankcard_add;
	/** 持卡人姓名 */
	private EditText yhzx_sc_et_bankcard_name;
	/** 银行卡号 */
	private EditText yhzx_sc_et_bankcard_number;
	/** 开户银行 */
	private Spinner yhzx_sc_spn_bankcard_bank;
	/** 省 */
	private Spinner yhzx_sc_spn_bankcard_province;
	/** 市 */
	private Spinner yhzx_sc_spn_bankcard_city;
	/** 确认添加按钮 */
	private Button yhzx_sc_btn_submit;

	/** 省市级联解析器 */
	private ProvinceParse parse;
	/** 当前选择省 */
	private Province currentProvince;
	/** 当前选择市 */
	private City currentCity;

	/** 银行列表 */
	ArrayAdapter<Bank> bankAdapter;
	private List<Bank> bankList = new ArrayList<Bank>();
	/** 当前选择银行 */
	private Bank currentBank;

	/** 真实姓名 */
	private String realname;
	/** 银行卡号 */
	private String bankcard;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.yhzx_sc_bank_card);

		titleBar();
		initView();
		initData();

		// System.out.println("ApplicationData.getInstance().getRealName() = ["
		// + ApplicationData.getInstance().getRealName() + "]");
		// System.out.println("ApplicationData.getInstance().isIsMobileValied() = ["
		// + ApplicationData.getInstance().isIsMobileValied() + "]");
		// System.out.println("ApplicationData.getInstance().getIDCardNumber() = ["
		// + ApplicationData.getInstance().getIDCardNumber() + "]");

		if ("".equals(ApplicationData.getInstance().getRealName()) || !ApplicationData.getInstance().isIsMobileValied()
				|| "".equals(ApplicationData.getInstance().getIDCardNumber())) {
			showTip("请先完善手机号码，真实姓名，身份证后再进行银行卡的绑定。");
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (!ApplicationData.getInstance().getCardNum().equals("")) {
			view_sc_bankcard_info.setVisibility(View.VISIBLE);
			view_sc_bankcard_add.setVisibility(View.GONE);
		} else {
			view_sc_bankcard_info.setVisibility(View.GONE);
			view_sc_bankcard_add.setVisibility(View.VISIBLE);
		}
		
	}

	public void onPause() {
		super.onPause();
		
	}

	/**
	 * 初始化数据
	 */
	private void initData() {
		if (!ApplicationData.getInstance().getCardNum().equals("")) {
			// view_sc_bankcard_info.setVisibility(View.VISIBLE);
			// view_sc_bankcard_add.setVisibility(View.GONE);

			// yhzx_sc_tv_bankcard_name.setText(ApplicationData.getInstance().getRealName());
			if (!"".equals(ApplicationData.getInstance().getRealName()))
				yhzx_sc_tv_bankcard_name.setText(ApplicationData.getInstance().getRealName().substring(0, 1) + "***");
			yhzx_sc_tv_bankcard_addr.setText(ApplicationData.getInstance().getBankName());
			yhzx_sc_tv_bankcard_number.setText(ApplicationData.getInstance().getCardNum());
		} else {
			// view_sc_bankcard_info.setVisibility(View.GONE);
			// view_sc_bankcard_add.setVisibility(View.VISIBLE);

			bankAdapter = new ArrayAdapter<Bank>(this, R.layout.simple_spinner_item, android.R.id.text1, bankList);
			yhzx_sc_spn_bankcard_bank.setAdapter(bankAdapter);
			yhzx_sc_spn_bankcard_bank.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
				@Override
				public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
					currentBank = bankList.get(position);
				}

				@Override
				public void onNothingSelected(AdapterView<?> parent) {
				}
			});

			AsyncLoader_bank bankTask = new AsyncLoader_bank();
			bankTask.execute("13");

			parse = ProvinceParse.build(this, R.raw.province, R.raw.cities);
			ArrayAdapter<Province> provinceAdapter = new ArrayAdapter<Province>(this, R.layout.simple_spinner_item,
					android.R.id.text1, parse.getProvinces());
			yhzx_sc_spn_bankcard_province.setAdapter(provinceAdapter);

			yhzx_sc_spn_bankcard_province.setOnItemSelectedListener(new ProvinceAdapter());
			yhzx_sc_spn_bankcard_city.setOnItemSelectedListener(new CityAdapter());

			yhzx_sc_spn_bankcard_province.setSelection(14);
		}
	}

	public void onProvinChange(int position) {
		currentProvince = parse.getProvinces().get(position);
		ArrayAdapter<City> cityAdapter = new ArrayAdapter<City>(this, R.layout.simple_spinner_item, android.R.id.text1,
				currentProvince.getCities());
		yhzx_sc_spn_bankcard_city.setAdapter(cityAdapter);
	}

	class ProvinceAdapter implements OnItemSelectedListener {
		@Override
		public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
			onProvinChange(position);

			if (position == 14) {
				yhzx_sc_spn_bankcard_city.setSelection(5);
			}
		}

		@Override
		public void onNothingSelected(AdapterView<?> parent) {

		}
	}

	final class CityAdapter extends ProvinceAdapter {
		@Override
		public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
			currentCity = currentProvince.getCities().get(position);
		}
	}

	/**
	 * 初始化组件
	 */
	private void initView() {
		view_sc_bankcard_info = findViewById(R.id.view_sc_bankcard_info);
		yhzx_sc_tv_bankcard_name = (TextView) findViewById(R.id.yhzx_sc_tv_bankcard_name);
		yhzx_sc_tv_bankcard_addr = (TextView) findViewById(R.id.yhzx_sc_tv_bankcard_addr);
		yhzx_sc_tv_bankcard_number = (TextView) findViewById(R.id.yhzx_sc_tv_bankcard_number);

		view_sc_bankcard_add = findViewById(R.id.view_sc_bankcard_add);
		yhzx_sc_et_bankcard_name = (EditText) findViewById(R.id.yhzx_sc_et_bankcard_name);
		yhzx_sc_et_bankcard_number = (EditText) findViewById(R.id.yhzx_sc_et_bankcard_number);
		yhzx_sc_spn_bankcard_bank = (Spinner) findViewById(R.id.yhzx_sc_spn_bankcard_bank);
		yhzx_sc_spn_bankcard_province = (Spinner) findViewById(R.id.yhzx_sc_spn_bankcard_province);
		yhzx_sc_spn_bankcard_city = (Spinner) findViewById(R.id.yhzx_sc_spn_bankcard_city);
		yhzx_sc_btn_submit = (Button) findViewById(R.id.yhzx_sc_btn_submit);
		yhzx_sc_btn_submit.setOnClickListener(btn_onclick);
	}

	private View.OnClickListener btn_onclick = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.yhzx_sc_btn_submit:
				if ("".equals(ApplicationData.getInstance().getRealName())
						|| !ApplicationData.getInstance().isIsMobileValied()
						|| "".equals(ApplicationData.getInstance().getIDCardNumber())) {
					showTip("请先完善手机号码，真实姓名，身份证后再进行银行卡的绑定。");
					return;
				}

				realname = yhzx_sc_et_bankcard_name.getText().toString();
				bankcard = yhzx_sc_et_bankcard_number.getText().toString();
				if (realname.length() < 1) {
					yhzx_sc_et_bankcard_name.setError("请输入您的真实姓名");
				} else if (bankcard.length() < 1) {
					yhzx_sc_et_bankcard_number.setError("请输入您的银行卡号");
				} else {
					AsyncLoader task = new AsyncLoader();
					task.execute("105");
				}
				break;
			}
		}
	};

	/**
	 * 获取银行列表
	 */
	private class AsyncLoader_bank extends AsyncTask<String, Integer, String> {
		@Override
		protected void onPreExecute() {
		}

		@Override
		protected String doInBackground(String... params) {
			String action = params[0];
			String strResult;

			JSONObject param = new JSONObject();
			String UserID = ApplicationData.getInstance().getUserID();
			strResult = GetRequestParams.getRequestUserIDResult(param.toString(), UserID, action,
					getApplicationContext());
			return strResult;
		}

		@Override
		protected void onPostExecute(String result) {
			try {
				if (null != result) {
					JSONTokener jsonParser = new JSONTokener(result);
					JSONObject js = (JSONObject) jsonParser.nextValue();
					if (js.getInt("Code") == 0) {
						List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
						list = ConvertJsonToList.getList(js.getString("Data"));
						for (int j = 0; j < list.size(); j++) {
							Map<String, Object> map = list.get(j);
							Bank bank = new Bank(map.get("Name").toString(), Integer.parseInt(map.get("ID").toString()));
							bankList.add(bank);
						}
					}
				}
			} catch (JSONException e) {
				// e.printStackTrace();
			} finally {
				bankAdapter.notifyDataSetChanged();
			}
		}

	}

	/**
	 * 绑定银行卡
	 */
	private class AsyncLoader extends AsyncTask<String, Integer, String> {
		ShowTipDialog showdialog = new ShowTipDialog();

		@Override
		protected void onPreExecute() {
			showdialog.showDialog(ScBankCardActivity.this);
		}

		@Override
		protected String doInBackground(String... params) {
			String action = params[0];
			String strResult;

			try {
				JSONObject param = new JSONObject();
				 param.put("bankID", currentBank.getCode());
				 param.put("bankCardNumber", bankcard);
				 param.put("bankProvinceID", currentProvince.getCode());
				 param.put("bankCityID", ""+currentCity.getCode());
				 param.put("bankUserName", realname);
				 param.put("BankTypeID", 2);

//				param.put("BankName", currentBank.getName());
//				param.put("BankCardNumber", bankcard);
//				param.put("ProvinceName", currentProvince.getName());
//				param.put("CityName", currentCity.getName());
//				param.put("RealityName", realname);
//				param.put("BankTypeID", currentBank.getCode());

				String UserID = ApplicationData.getInstance().getUserID();
				strResult = GetRequestParams.getRequestUserIDResult(param.toString(), UserID, action,
						getApplicationContext());
				return strResult;
			} catch (JSONException e) {
				// e.printStackTrace();
				return null;
			}
		}

		@Override
		protected void onPostExecute(String result) {
			try {
				if (null != result) {
					JSONTokener jsonParser = new JSONTokener(result);
					JSONObject js = (JSONObject) jsonParser.nextValue();
					String data = js.getString("Data");
					showTip(data);
					if (js.getInt("Code") == 0) {
						ApplicationData.getInstance().setBankName(
								currentProvince.getName() + " " + currentCity.getName() + " " + currentBank.getName());
						ApplicationData.getInstance().setCardNum(
								bankcard.substring(0, 3) + "******" + bankcard.substring(bankcard.length() - 3));

						yhzx_sc_tv_bankcard_name.setText(ApplicationData.getInstance().getRealName().substring(0, 1)
								+ "***");
						yhzx_sc_tv_bankcard_addr.setText(ApplicationData.getInstance().getBankName());
						yhzx_sc_tv_bankcard_number.setText(ApplicationData.getInstance().getCardNum());

						view_sc_bankcard_info.setVisibility(View.VISIBLE);
						view_sc_bankcard_add.setVisibility(View.GONE);
					}
				}
			} catch (JSONException e) {
				// e.printStackTrace();
			} finally {
				showdialog.closeDialog();
			}
		}

	}

	/** TitleBar标题栏 */
	public void titleBar() {
		TextView info = (TextView) findViewById(R.id.top_title_info);
		info.setText(R.string.yhzx_sc_bank_card);
		TextView back = (TextView) findViewById(R.id.top_title_back);
		back.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
	}

	/** 显示文字提示 */
	private void showTip(String tip) {
		Toast.makeText(this, tip, Toast.LENGTH_SHORT).show();
	}

	/**
	 * 银行内部类
	 */
	private class Bank {
		/** 银行名称 */
		private String name;
		/** 银行代码 */
		private int code;

		public Bank(String name, int code) {
			this.name = name;
			this.code = code;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public int getCode() {
			return code;
		}

		public void setCode(int code) {
			this.code = code;
		}

		@Override
		public String toString() {
			return name;
		}

	}

}
